package com.example.lotapp.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.text.TextUtils;

public class FileUtils {
	public static boolean createFolder(String path) {
		File dir = new File(path);
		if( dir.exists() == false ) {
			dir.mkdirs();
			return true;
		}
		return false;
	}

	public static void createParentFolder(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return ;
		}
		File file = new File(filePath);
		if (file.exists()) {
			return ;
		}
		File dir = file.getParentFile();
		if (dir != null) {
			dir.mkdirs();
		}
	}

	public static String readFile(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return "";
		}
		File file = new File(filePath);
		if (!file.exists()) {
			return "";
		}
		try {
			return getInputStreamStr(new FileInputStream(file));
		} catch(IOException e) {
			return "";
		}
	}
	
	public static String getInputStreamStr(InputStream input) {
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
			String line;
			while (null != (line = br.readLine())) {
				stringBuilder.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch(IOException e) {
			}
		}
		return stringBuilder.toString();
	}

	public static boolean writeFile(String localPath, byte[] data) {
		if (TextUtils.isEmpty(localPath) || data == null) {
			return false;
		}
		File localFile = new File(localPath);
		FileOutputStream out = null;
		try {
			FileUtils.createParentFolder(localPath);
			if (!localFile.exists() && !localFile.createNewFile()) {
				return false;
			}
			out = new FileOutputStream(localFile);
			out.write(data);
			out.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			localFile.delete();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
			}
		}
		return false;
	}
	
	
	public static String getAssetsFileContent(Context context, String fileName) {
		try {
			return getInputStreamStr(context.getAssets().open(fileName));
		} catch (IOException e) {
		}
		return "";
	}
}
